<template>
  <div v-drag>
    <div class="mask" @click="closePopup(false)"></div>
    <div class="edit_box" id="change_width" v-loading="loading">
      <div class="box_head">
        <p>下单</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">
        <div v-if="step===1">
          <div class="line">
            <span class="lab"><i class="mark_icon" v-if="!$route.query.userId">*</i>用户：</span>
            <div>
              <userSelect @listenToUser="getAddress" :uId="userId" v-if="!$route.query.userId"/>
              <p v-else>{{$route.query.username}}</p>
            </div>
          </div>
          <div class="line">
            <span class="lab"><i class="mark_icon">*</i>配送地址：</span>
            <div>
              <el-select
                filterable
                v-model="address"
                @change="clearNum"
                placeholder="请选择配送地址">
                <el-option
                  v-for="(item,index) in addressOption"
                  :key="index"
                  :label="item.address"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="line">
            <span class="lab">备注：</span>
            <div>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入备注"
                v-model="remark">
              </el-input>
            </div>
          </div>
        </div>

        <div v-else>
          <div class="line">
            <div class="g-mt-10">
              <a class="common_btn el-icon-delete" @click="clearNum()"></a>
              <a class="common_btn el-icon-circle-plus-outline" @click="addProNum()"></a>
            </div>
          </div>
          <div>
            <div v-for="(link,index) in proNum" :key="index" class="input-box g-mb-10" id="link"
                 @mouseenter="showDel(index)" @mouseleave="delNum=null">
              <div class="input_box">
                <div :class="errIndex == index ? 'error_border select_box' : 'select_box'" ref="input">
                  <el-select
                    filterable
                    ref="linkName"
                    :popper-append-to-body="false"
                    v-model="link.productId"
                    @change="judgeInfo($event,index)"
                    placeholder="请选择商品" @focus="getIndex($event,index)">
                    <span v-if="link.productId == ''">
                    <el-option
                      v-for="(item,index) in list"
                      :key="index"
                      :label="item.productName"
                      :value="item.productId">
                    </el-option>
                      </span>
                    <span v-else>
                    <el-option
                      v-for="(item,index) in finalProductList"
                      :key="index"
                      :label="item.productName"
                      :value="item.productId">
                    </el-option>
                      </span>
                  </el-select>
                </div>
                <div class="num_box">
                  <span class="minus_btn" @click="deleteProduct(index)">
                    <i class="el-icon-minus" :class="{'lose':parseFloat(link.numbers) <=1}"></i>
                  </span>
                  <input class="num_show" type="number" v-model="link.numbers" min="0"/>
                  <span class="plus_btn" @click="addProduct(index)">
                    <i class="el-icon-plus"></i>
                  </span>
                </div>
                <!--只有一条的时候，不显示删除-->
                <i class="delSingle el-icon-remove-outline" @click="delSingleInput(index)"></i>
              </div>
              <p class="limit_box" v-show="!!link.productId">拥有水票<i :id="'num'+index">{{ link.waterVote }}</i>张,可用额度<i
                :id="'residue'+index">{{ link.waterLines }}</i></p>
            </div>
          </div>
        </div>
        <p class="error_line" :class="{'specail_error':step===2}">{{ tipText }}</p>
      </div>
      <div class="box_foot" v-if="step===1">
        <span @click="closePopup(false)">取消</span>
        <span @click="setStep(2)">下一步</span>
      </div>
      <div class="box_foot" v-else>
        <span @click="step=1;tipText='';">上一步</span>
        <span @click="confirmEdit">确定</span>
      </div>
    </div>
  </div>
</template>

<script>
import {getAllUserProduct} from "@/api/data/user/product";
import {createData} from "@/api/data/user/productSend";
import {getAllAddress} from "@/api/data/user/address";
import userSelect from '../../../components/user/index'

export default {
  components:{
    userSelect
  },
  data() {
    return {
      step: 1,
      loading: false,
      tipText: '',
      userId: '',
      finalProductList: [],
      list: [],
      isFinal: false,
      address: '',
      addressOption: [],
      proNum: [{
        numbers: '',
        productId: '',
      }],
      test: [],
      delNum: null,
      isSame: false,
      errIndex: undefined,
      remark:''
    }
  },
  mounted() {
    if (this.$route.query.userId){
      this.userId = this.$route.query.userId;
      this.getAddress(this.$route.query.userId);
    }
  },
  methods: {
    getProduct(data) {
      let queryParams = {
        userId: this.userId
      }
      if (data) {
        queryParams.productIds = data;
      }
      getAllUserProduct(queryParams).then((res) => {
        this.list = res ? res : [];
        if (!this.isFinal) {
          this.finalProductList = res ? res : [];
          this.isFinal = true;
        }
      })
    },

    getIndex(e, index) {
      this.proNum[index].productId = '';
      //重新获取当前的数据
      this.getNewAllProduct();
    },
    getNewAllProduct() {
      // 重新获取列表
      let arr = []
      this.proNum.forEach((item, index) => {
        if (item.productId != '') {
          arr.push(item.productId)
        }
        return arr
      })
      arr = arr.join(',')
      this.getProduct(arr);
    },

    // 获取用户id和地址
    getAddress(e) {
      this.userId = e;
      this.tipText = '';
      this.address = '';
      getAllAddress({userId: e}).then(res => {
        this.addressOption = res ? res : [];
      }).catch((e) => {
        this.addressOption = [];
      })
      this.clearNum();
    },

    setStep(type) {
      if (type === 2) {
        if (this.userId === '') {
          this.tipText = '请先选择订单用户'
        } else if (this.address === '') {
          this.tipText = '请先选择配送地址'
        } else {
          this.step = type;
          this.isFinal = false;
          this.getProduct();
        }
      }
    },

    judgeInfo(val, index) {
      let that = this;
      that.tipText = '';
      that.isSame = false;
      that.list.forEach((item, i) => {
        if (val === item.productId) {
          // document.getElementById('num'+index).innerHTML = item.numbers;
          // document.getElementById('residue'+index).innerHTML = item.authNumber - (item.usedAuthNumber);
          that.proNum[index].waterVote = item.numbers;
          that.proNum[index].waterLines = parseInt(item.authNumber - (item.usedAuthNumber));
          that.proNum[index].maxNum = parseInt(item.numbers + item.authNumber - (item.usedAuthNumber));
          that.proNum[index].numbers = item.minSendNumber;
          //记录起送量
          that.proNum[index].minSendNumber = item.minSendNumber;
        }
      })
      for (let i = 0; i < that.proNum.length - 1; i++) {
        for (let j = i + 1; j < that.proNum.length; j++) {
          if (that.proNum[i].productId === that.proNum[j].productId) {
            that.tipText = '不能选择两种相同的商品';
            that.isSame = true;
          }
        }
      }
    },

    closePopup(refresh) {
      this.$emit('listenToChild', {refresh:refresh})
    },

    confirmEdit() {
      let that = this;
      if (that.isSame) {
        that.tipText = '不能选择两种相同的商品';
      } else {
        let error = 0;
        that.proNum.forEach((item, index) => {
          if (!item.productId) {
            that.$refs.input[index].className = 'error_border';
            that.tipText = '请选择商品或者删除不需要的商品';
            error++;
          }
        })
        if (error === 0) {
          //判断最大最小数值
          that.judgeMaxNum();
        }
      }
    },
    judgeMaxNum() {
      let that = this;
      var proLen = that.proNum.length - 1;
      var proLenth = that.proNum.length;
      for (let i = 0; i < proLenth; i++) {
        if (that.proNum[i].numbers < that.proNum[i].minSendNumber) {
          that.errIndex = i;
          that.tipText = '商品最低数量为' + that.proNum[i].minSendNumber + '!'
          return;
        } else if (that.proNum[i].numbers > that.proNum[i].maxNum) {
          that.errIndex = i;
          that.tipText = '可使用余额不足,请重新确认数量!'
          return;
        } else {
          if (proLen == i) {
            that.errIndex = undefined;
            that.tipText = ''
            //删除多余字段
            that.formatProNum();
          }
        }
      }
    },
    //删除数组多余字段
    formatProNum() {
      let that = this;
      let index = that.proNum.length - 1;
      that.proNum.forEach((item, i) => {
        delete item.maxNum;
        delete item.waterVote;
        delete item.waterLines;
        if (i == index) {
          //提交数据
          that.createUserOrder();
        }

      })
    },

    createUserOrder() {
      this.loading = true;
      let param = {
        userId: this.userId,
        addressId: this.address,
        remark:this.remark,
        productInfo: this.proNum
      }
      createData(param).then(res => {
        this.$message.success({
          message: '操作成功',
          duration: 1500
        });
        this.closePopup(true);
        this.loading = false;
      }).catch((e) => {
        this.loading = false;
      })
    },

    deleteProduct(index) {
      let num = this.proNum[index].numbers;
      this.proNum[index].numbers = parseFloat(num) <= 1 ? 1 : parseFloat(num) - 1;
    },

    addProduct(index) {
      // let limit = document.getElementById('num' + index).innerHTML;
      // let max = limit ? parseFloat(limit) : 0;
      let max = this.proNum[index].maxNum;
      let num = parseFloat(this.proNum[index].numbers)
      this.proNum[index].numbers = !max || num < max ? num + 1 : num;
    },

    /*添加*/
    addProNum() {
      let cope = {numbers: '', productId: ''};
      this.proNum.push(cope);
      this.tipText = '';
    },

    /*清除*/
    clearNum() {
      this.proNum = [];
      for (const i in this.$refs.input) {
        this.$refs.input[i].className = ''
      }
      let cope = {numbers: '', productId: ''};
      this.proNum.push(cope);
      this.tipText = '';
    },

    // 单个删除
    delSingleInput(index) {
      this.proNum.splice(index, 1);
      this.tipText = '';
    },

    showDel(index) {
      this.delNum = index + 1;
      /*只有一条的时候，不加删除文字，可清空*/
      if (this.proNum.length == 1) {
        this.delNum = null
      }
    },
  }
}
</script>

<style scoped>
.box_body {
  min-height: 400px;
}

.input_box {
  display: flex;
  align-items: center;
  position: relative;
}

.line .link-input {
  line-height: 36px;
  border-radius: 4px;
  outline: none;
}

* {
  box-sizing: border-box;
}

.g-mb-10 {
  margin-bottom: 10px;
}

.g-ml-15 {
  margin-left: 15px;
}

a {
  text-decoration: none;
}

.link-txt {
  margin-right: 12px;
  width: 15px;
  float: left;
}

.link-input {
  width: 250px;
  height: 36px;
  background-color: #ffffff;
  border-radius: 2px;
  border: solid 1px #dcdcdc;
  padding-left: 15px;
  float: left;
  display: block;
  font-size: 14px;
  padding-right: 35px;
}

.common_btn {
  font-size: 24px;
  cursor: pointer;
  color: #6687f9;
  margin-right: 5px;
}

.delSingle {
  position: absolute;
  top: 10px;
  right: 18px;
  cursor: pointer;
  font-size: 22px;
  color: #e40000;
}

.num_box {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  overflow: hidden;
  margin-left: 30px;
}

.minus_btn, .plus_btn {
  width: 34px;
  display: inline-block;
  height: 34px;
  line-height: 34px;
  text-align: center;
  cursor: pointer;
}

.minus_btn i, .plus_btn i {
  color: #6687f9;
}

.minus_btn {
  border-right: 1px solid #DCDFE6;
}

.plus_btn {
  border-left: 1px solid #DCDFE6;
}

.lose {
  color: #DCDFE6 !important;
}

.num_show {
  max-width: 80px;
  min-width: 40px;
  line-height: 34px;
  text-align: center;
  border: none;
  outline: none;
}

.limit_box {
  margin-top: 10px;
  font-size: 14px;
  color: #6687f9;
}

.specail_error {
  padding-left: 0;
  margin-top: 30px;
}
</style>
